#include "event_app.h"
#include "protocol_app.h"
#include "bluetooth_board.h"
#include "device_parameter.h"

void BluetoothGetMacAddress(uint8_t *pMacOut)
{
  uint8_t MacAddr[MAC_ADDR_CODING_LENGTH] = {0};

  if (pMacOut != NULL)
  {
    FLASH_GetMACAddress(MacAddr);
    for (uint8_t i = 0; i < MAC_ADDR_CODING_LENGTH; i++)
    {
      pMacOut[i] = MacAddr[(MAC_ADDR_CODING_LENGTH - 1) - i];
    }
  }
}

uint32_t BluetoothGetUpdateRadioInterval(void)
{
  return (GetBluetoothUpdateRaidioInterval() * 60) * 1000;
}

void BluetoothPostConnectionActions(void)
{
  EventSetBluetoothConnectFlagBit(true);
  EventStartStadnbyTask();
}

void BluetoothPostDisconnectionActions(void)
{
  EventExitStadnbyTask();
  EventSetBluetoothConnectFlagBit(false);
}

uint8_t BluetoothGetDeviceType(void)
{
  return GetObtainTheDeviceModel();
}

uint8_t BluetoothGetSystemStatus(void)
{
  return GetDeviceInitStatus();
}

void BluetoothGetRadioName(void *pNameOut)
{
  uint8_t DeviceInitStatus = GetDeviceInitStatus() & (~FIRMWARE_UPGRADE);
  if (DeviceInitStatus == NORMAL_MODE)
  {
    char RadioName[30] = {0};

    uint32_t RoomNumberId = GetLockRoomIdNumber();
    sprintf(RadioName, "%d", RoomNumberId);

    uint8_t RadioNameLen = strlen(RadioName);
    if (RadioNameLen > 9)
    {
      RadioNameLen = 9;
    }

    uint8_t SubroomNumberId = GetLockSubroomNumber();
    if (SubroomNumberId > 0)
    {
      if (SubroomNumberId > 26)
      {
        SubroomNumberId = 26;
      }

      RadioName[RadioNameLen++] = (SubroomNumberId - 1) + 'A';
    }

    memcpy(pNameOut, RadioName, RadioNameLen);
  }
  else
  {
    memcpy(pNameOut, DEFAULT_BLUETOOTN_RADIO_NAME, strlen(DEFAULT_BLUETOOTN_RADIO_NAME));
  }
}

uint8_t BluetoothGetProtocolVersion(void)
{
  return PROTOCOL_VERSION_CONTORL;
}

uint8_t BluetoothGetEventToBeSendFlagBit(void)
{
  if (EventGetLogNeedToBeUploadedFlagBit() == true)
    return LOG_AVAILABLE;

  return NO_LOG_AVAILABLE;
}

uint8_t BluetoothGetBatteyLevel(void)
{
  return 100;//BatteryGetVoltagePercentage();
}

uint16_t BluetoothGetConnectTimeout(void)
{
  uint16_t ConnectTimeout = GetBluetoothConnectionTimeout();
  if ((ConnectTimeout < MIX_CONNECTION_TIMEOUT) || (ConnectTimeout > MAX_CONNECTION_TIMEOUT))
  {
    ConnectTimeout = DEFAULT_CONNECTION_TIMEOUT;
  }

  return ConnectTimeout * 1000;
}

uint16_t BluetoothGetBroadcastInterval(void)
{
  return BLUETOOTH_BROADCAST_INTERVAL;
}

void BluetoothAnalysisServerPushMessage(const uint8_t *pMessageIn, const uint16_t SizeOfMessage)
{
  ProtocolPraseMessage(SOURCE_MOBILE_CLIENT, pMessageIn, SizeOfMessage);
}
